import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import { LoadingBar } from 'view-design'

/* Layout */
import AppLayout from '@/layout/index.vue'

/* Router modules */
import { libraryRouter } from './modules/library'
import { userRouter } from './modules/user'
import { UserModule } from '@/store/modules/user'

Vue.use(VueRouter)

/**
 * meta: {
 *  title: 'Title'                  The name showed in page title, sidebar menu and breadcrumb (recommend set).
 *  icon: 'icon-name' | Svg         The icon showed in the sidebar.
 *  svg: false                      If true, the icon will be showed by using vue-svgicon.
 *                                  Otherwise, it will be treated as an icon font.
 *  activeMenu: 'RouteName'         If set, the sidebar will highlight the menu you set.
 *  menu: false                     if true, it will be added to the sidebar menu. (Can't be in children!)
 * }
 */
export const routes: RouteConfig[] = [
  {
    name: 'Index',
    path: '/',
    component: AppLayout,
    redirect: '/index',
    meta: {
      title: '首页',
      icon: 'md-home',
      menu: true
    },
    children: [
      {
        path: 'index',
        component: () => import(/* webpackChunkName: "index" */ '@/views/index/index.vue'),
        meta: {
          title: '首页',
          icon: 'md-home'
        }
      },
      ...userRouter
    ]
  },
  {
    name: 'Login',
    path: '/login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/login/index.vue'),
    meta: {
      title: '登录'
    }
  },
  libraryRouter
]

const router = new VueRouter({
  mode: process.env.NODE_ENV === 'production' ? 'history' : 'hash',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  LoadingBar.start()
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = `${to.meta.title} - 音域 VitMusic`
  } else {
    document.title = '音域 VitMusic'
  }
  next()
})

router.beforeEach((to, from, next) => {
  if (UserModule.token !== '' && UserModule.id === '') {
    UserModule.GetUserInfo()
  }
  next()
})

router.afterEach(() => {
  LoadingBar.finish()
})

export default router
